    //
//  MapViewController_iPad.m
//  Tazama NGO
//
//  Created by jsheriff on 3/2/11.
//  Copyright 2011 The MITRE Corporation. All rights reserved.
//

#import "MapViewController_iPad.h"
#import "FieldObservationDB.h"
#import "FieldObservationAnnotation.h"
#import "Notifications.h"
#import "FieldObservationViewController.h"
#import "KmlElementDB.h"
#import "ResourceRequisitionAnnotation.h"
#import "KmlPlacemarkViewController_iPad.h"

#import "SettingsViewController_iPad.h"
#import "Settings.h"

@interface MapViewController_iPad ()

- (void)addKmlPlacemarksToMap;
- (void)updateKmlPlacemarks:(NSNotification *)notification;
- (void)handleLongPress:(UIGestureRecognizer *)sender;
- (void)finishSearchWithString:(NSString *)searchString;

@end

@implementation MapViewController_iPad

@synthesize popoverController;
@synthesize fieldObservationEditViewController;
@synthesize searchResultsViewController;
@synthesize searchResultsPopoverController;
@synthesize toolbar;
@synthesize mapView;
@synthesize searchBar;
@synthesize centerOnUser;
@synthesize initialUserLocation;

 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
}
*/

- (void)viewDidLoad {
    mapView.delegate = self;
	mapView.mapType = MKMapTypeHybrid;
	centerOnUser = NO;
	initialUserLocation = YES;
    
    // Hook up the long press gesture recognizer
    UILongPressGestureRecognizer *longPressGestureRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];
    [mapView addGestureRecognizer:longPressGestureRecognizer];
    [longPressGestureRecognizer release];
    longPressActive = NO;
    
    // Hook up the search bar
    searchBar.delegate = self;
        
//    [self addMessagesToMap];
//    [self addRequestsToMap];
    [self addKmlPlacemarksToMap];
	
//	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(displayMessageOnMap:) name:kDisplayMessageOnMapNotification object:nil];
//	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateMessages:) name:kFieldObservationDatabaseUpdateKey object:nil];
//	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateResourceRequisitions:) name:kResourceRequisitionDatabaseUpdateKey object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateKmlPlacemarks:) name:kKmlDatabaseUpdateKey object:nil];
    //	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mapSelectionChanged:) name:kMapSelectionChanged object:nil];
    
    // Create and configure the recent searches controller.
    searchResultsViewController = [[SearchResultsViewController_iPad alloc] initWithStyle:UITableViewStylePlain];
    searchResultsViewController.delegate = self;
    
    // note: the search results UIPopoverController will be created later on demand
    
    [super viewDidLoad];
}

-(IBAction)settingsBtnClick:(id)sender {
    SettingsViewController_iPad *settingsController = [[SettingsViewController_iPad alloc] initWithNibName:@"SettingsViewController_iPad" bundle:nil];
    settingsController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    [self presentModalViewController:settingsController animated:YES];
    [settingsController release];
    
}
-(IBAction)currLocClick:(id)sender {
    //Center the map on the current location
    if (mapView.userLocation) {
        [mapView setCenterCoordinate:mapView.userLocation.coordinate animated:YES];
    }
    
}

- (void)mapView:(MKMapView *)localMapView didUpdateUserLocation:(MKUserLocation *)userLocation {
	// Filter spurious values
	if (userLocation.coordinate.latitude > 90.0 || userLocation.coordinate.longitude < -90.0) {
		NSLog(@"didUpdateUserLocation returned bad latitude");
		return;
	}
	
	if (initialUserLocation || centerOnUser) {
		MKCoordinateRegion region;
		region.center = userLocation.coordinate;
		region.span.latitudeDelta = .06;
		region.span.longitudeDelta = .06;
		
		[mapView setRegion:region animated:YES];
		
		initialUserLocation = NO;
	}
}

- (MKAnnotationView *)mapView:(MKMapView *)localMapView viewForAnnotation:(id <MKAnnotation>)annotation {
	if ([annotation isKindOfClass:[MKUserLocation class]]) {
        return nil;
	}
	else if ([annotation isKindOfClass:[FieldObservationAnnotation class]]) {
        //		FieldObservationAnnotation *foAnnotation = annotation;
		MKAnnotationView *annotationView = [localMapView dequeueReusableAnnotationViewWithIdentifier:@"FieldObservationAnnotationView"];
		if (annotationView == nil)
		{
			annotationView = [[[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"FieldObservationAnnotationView"] autorelease];
		}
		
		annotationView.annotation = annotation;
		UIImageView	 *foImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"MagnifyingGlassMarker40.png"]];
		[annotationView addSubview:foImageView];
		annotationView.image = [UIImage imageNamed:@"Transparent33.png"];
		annotationView.canShowCallout = YES;
		[annotationView setRightCalloutAccessoryView:[UIButton buttonWithType:UIButtonTypeDetailDisclosure]];
        annotationView.centerOffset = CGPointMake(0.0, -23.0);
		return annotationView;
	}
	else if ([annotation isKindOfClass:[ResourceRequisitionAnnotation class]]) {
        //		FieldObservationAnnotation *foAnnotation = annotation;
		MKAnnotationView *annotationView = [localMapView dequeueReusableAnnotationViewWithIdentifier:@"ResourceRequisitionAnnotationView"];
		if (annotationView == nil)
		{
			annotationView = [[[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"ResourceRequisitionAnnotationView"] autorelease];
		}
		
		annotationView.annotation = annotation;
		UIImageView	 *foImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"QuestionMarkMarker40.png"]];
		[annotationView addSubview:foImageView];
		annotationView.image = [UIImage imageNamed:@"Transparent33.png"];
		annotationView.canShowCallout = YES;
        //		[annotationView setRightCalloutAccessoryView:[UIButton buttonWithType:UIButtonTypeDetailDisclosure]];
        annotationView.centerOffset = CGPointMake(0.0, -23.0);
		return annotationView;
	}
    else if ([annotation isKindOfClass:[MKPointAnnotation class]]) {
        MKAnnotationView *annotationView = [[KmlElementDB sharedInstance] viewForAnnotation:annotation];
        annotationView.canShowCallout = YES;
		[annotationView setRightCalloutAccessoryView:[UIButton buttonWithType:UIButtonTypeDetailDisclosure]];
		return annotationView;
    }
	else {
        NSLog(@"annotation class = %@", NSStringFromClass([annotation class]));
		return nil;
	}
    
}

- (void)splitViewController: (UISplitViewController*)svc willHideViewController:(UIViewController *)aViewController withBarButtonItem:(UIBarButtonItem*)barButtonItem forPopoverController: (UIPopoverController*)pc {
    barButtonItem.title = @"Messages";
    NSMutableArray *items = [[toolbar items] mutableCopy];
    [items insertObject:barButtonItem atIndex:0];
    [toolbar setItems:items animated:YES];
    [items release];
    self.popoverController = pc;
}

// Called when the view is shown again in the split view, invalidating the button and popover controller.
- (void)splitViewController: (UISplitViewController*)svc willShowViewController:(UIViewController *)aViewController invalidatingBarButtonItem:(UIBarButtonItem *)barButtonItem {
    NSMutableArray *items = [[toolbar items] mutableCopy];
    [items removeObjectAtIndex:0];
    [toolbar setItems:items animated:YES];
    [items release];
    self.popoverController = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Overriden to allow any orientation.
    return YES;
}

-(void)displayMessageOnMap:(NSNotification *)notification {
	FieldObservation *fo = [[notification userInfo] objectForKey:kFieldObservationKey];	
	
	for (FieldObservationAnnotation *annotation in mapView.annotations)
	{
		if (CFEqual(annotation.fieldObservation.uuid, fo.uuid))
		{
			[self.popoverController dismissPopoverAnimated:YES];

			MKCoordinateSpan span = {0.02, 0.02};
			MKCoordinateRegion region = {annotation.coordinate, span};
			[mapView setRegion:region animated:YES];

			[mapView selectAnnotation:annotation animated:YES];
						
			return;
		}
	}
	
}

-(void)addKmlPlacemarksToMap {
    [mapView addAnnotations:[KmlElementDB sharedInstance].kmlAnnotationList];
    [mapView addOverlays:[KmlElementDB sharedInstance].kmlOverlayList];
}

-(void)updateKmlPlacemarks:(NSNotification *)notification {
    // Delete the old kml placemarks from the map
    NSMutableArray *annotationList = [[NSMutableArray alloc] init];
	for (id<MKAnnotation> annotation in mapView.annotations)
	{
        if ([annotation isKindOfClass:[MKPointAnnotation class]]) {
            [annotationList addObject:annotation];
        }
    }
    [mapView removeAnnotations:annotationList];
    
    // Add the updated kml placemarks to the map
    [self addKmlPlacemarksToMap];
}

- (void)mapView:(MKMapView *)theMapView annotationView:(MKAnnotationView *)annotationView calloutAccessoryControlTapped:(UIControl *)control {
    if ([annotationView.annotation isKindOfClass:[FieldObservationAnnotation class]]) {
        FieldObservationViewController *content = [[FieldObservationViewController alloc] init];
        FieldObservationAnnotation *annotation = annotationView.annotation;
        content.fieldObservation = annotation.fieldObservation;
        UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:content];
        
        popoverController = [[UIPopoverController alloc] initWithContentViewController:navigationController];
        popoverController.popoverContentSize = content.view.frame.size;
        [content release];
        
        [mapView deselectAnnotation:annotationView.annotation animated:YES];
        
        CGRect rect = [annotationView.superview convertRect:annotationView.frame toView:mapView];
        
        [popoverController presentPopoverFromRect:rect inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
    }
    else if ([annotationView.annotation isKindOfClass:[MKPointAnnotation class]]) {
        MKPointAnnotation *pointAnnotation = annotationView.annotation;
        
        // Create the view controller
        KmlPlacemarkViewController_iPad *kmlPlacemarkViewController = [[KmlPlacemarkViewController_iPad alloc] initWithNibName:@"KmlPlacemarkViewController_iPad" bundle:nil];
        kmlPlacemarkViewController.title = pointAnnotation.title;
        
        // Find the matching placemark
        for (KMLPlacemark *placemark in [[[KmlElementDB sharedInstance] kmlParser] _placemarks]) {
            if (placemark.mkShape == pointAnnotation) {
                //                NSString *html = @"<html><head><title>The Meaning of Life</title></head><body><p>...really is <b>42</b>!</p></body></html>";
                //                kmlPlacemarkViewController.htmlContent = html;
                kmlPlacemarkViewController.htmlContent = placemark.placemarkDescription;
                break;
            }
        }
        
        // Show the view controller
        UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:kmlPlacemarkViewController];
        navigationController.modalPresentationStyle = UIModalPresentationPageSheet;
        navigationController.navigationBar.barStyle = UIBarStyleType;
        
        [self presentModalViewController:navigationController animated:YES];
        [navigationController release];
        [kmlPlacemarkViewController release];
    }
    else
        NSLog(@"calloutAccessoryControlTapped for unknown annotation type");
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)aSearchBar {
    NSString *searchString = [searchBar text];
    [self finishSearchWithString:searchString];
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    // We've returned from the "No Results Found" alert view
    // Move the focus back to the search bar and restore the keyboard
    [searchBar becomeFirstResponder];
}

- (void)searchResultsViewController:(SearchResultsViewController_iPad *)controller didSelectPlacemark:(KMLPlacemark *)placemark {
    searchBar.text = placemark.name;
    
    // Jump to the placemark
    MKCoordinateSpan span = {0.03, 0.03};
    MKCoordinateRegion region = {placemark.geometry.mapkitShape.coordinate, span};
    [mapView setRegion:region animated:TRUE];
    
    // Expand the annotation           
    [mapView selectAnnotation:placemark.mkShape animated:YES];
    
    // Dismiss the keyboard
    [searchBar resignFirstResponder];

}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)aSearchBar {
    
    if (searchResultsPopoverController == nil) // create the popover if not already open
    {
        // Create a navigation controller to contain the recent searches controller,
        // and create the popover controller to contain the navigation controller.
        UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:self.searchResultsViewController];
        
        UIPopoverController *popover = [[UIPopoverController alloc] initWithContentViewController:navigationController];
        self.searchResultsPopoverController = popover;
        searchResultsPopoverController.delegate = self;
        
        // Ensure the popover is not dismissed if the user taps in the search bar.
        popover.passthroughViews = [NSArray arrayWithObject:searchBar];
        
        // Display the search results controller popover.
        [searchResultsPopoverController presentPopoverFromRect:[searchBar bounds] inView:searchBar permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
        
        [navigationController release];
        [popover release];
    }
}


- (void)searchBarTextDidEndEditing:(UISearchBar *)aSearchBar {
    
    // If the user finishes editing text in the search bar by, for example:
    // tapping away rather than selecting from the recents list, then just dismiss the popover
    //
    
    if (searchResultsPopoverController != nil)
    {
        [searchResultsPopoverController dismissPopoverAnimated:YES];
        self.searchResultsPopoverController = nil;
    }    
    [searchBar resignFirstResponder];
}


- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    // When the search string changes, filter the recents list accordingly.
    [searchResultsViewController filterResultsUsingString:searchText];
}

- (void)popoverControllerDidDismissPopover:(UIPopoverController *)popoverController {
    // Remove focus from the search bar without committing the search.
    [searchBar resignFirstResponder];
}

- (void)finishSearchWithString:(NSString *)searchString {
    // Find a matching KML Placemark.  We look for the first placemark name that contains the search string.
    for (KMLPlacemark *placemark in [[[KmlElementDB sharedInstance] kmlParser] _placemarks]) {
        if ([placemark.name rangeOfString:searchString options:NSCaseInsensitiveSearch].location != NSNotFound) {
            // Jump to the placemark
            MKCoordinateSpan span = {0.03, 0.03};
            MKCoordinateRegion region = {placemark.geometry.mapkitShape.coordinate, span};
            [mapView setRegion:region animated:TRUE];
            
            // Expand the annotation           
            [mapView selectAnnotation:placemark.mkShape animated:YES];
            
            // Dismiss the keyboard
            [searchBar resignFirstResponder];
            
            return;
        }
    }
    
    // No matching placemark found
    [searchBar resignFirstResponder];
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"No Results Found" message:nil delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alertView show];
    [alertView release];
}

- (void)handleLongPress:(UIGestureRecognizer *)sender {
    if (longPressActive) {
        return;
    }
    
    longPressActive = YES;
    NSLog(@"Long press recognized");
    CGPoint pressPoint = [sender locationInView:sender.view.superview];
    
    FieldObservation *fieldObservation = [[FieldObservation alloc] init];
    fieldObservation.messageId = @"";
    fieldObservation.messageSent = NO;
    fieldObservation.immediateNeeds = @"";
    fieldObservation.severity = @"";
    fieldObservation.confidence = @"";
    fieldObservation.observationText= @"";
    fieldObservation.location = [mapView convertPoint:pressPoint toCoordinateFromView:mapView];
    
    //            fieldObservation.location = CLLocationCoordinate2DMake(40.7553, 30.0698);
    
    fieldObservationEditViewController = [[FieldObservationEditViewController alloc] initWithStyle:UITableViewStyleGrouped];
    fieldObservationEditViewController.title = @"New Field Obsrvn";
    fieldObservationEditViewController.delegate = self;
    fieldObservationEditViewController.fieldObservation = fieldObservation;
    
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:fieldObservationEditViewController];
    navigationController.modalPresentationStyle = UIModalPresentationFormSheet;
    navigationController.navigationBar.barStyle = UIBarStyleBlackOpaque;
    
    [self presentModalViewController:navigationController animated:YES];
    [navigationController release];

}

-(void)didSaveFieldObservationEdit {
    [fieldObservationEditViewController.navigationController dismissModalViewControllerAnimated:YES];

    FieldObservation * fieldObservation = fieldObservationEditViewController.fieldObservation;
    fieldObservation.uuid = CFUUIDCreate(kCFAllocatorDefault);
    FieldObservationDB *db = [FieldObservationDB sharedInstance];
    [db addNewFieldObservation:fieldObservation];

    longPressActive = NO;
}

-(void)didCancelFieldObservationEdit {
    [fieldObservationEditViewController.navigationController dismissModalViewControllerAnimated:YES];
    longPressActive = NO;
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}


- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}


@end
